package com.ds.lens.data.security;

import com.ds.lens.data.common.constant.Constants;
import com.ds.lens.data.service.LensAuthService;
import com.ds.lens.data.service.dao.entity.LensUser;
import com.ds.lens.data.vo.in.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.ds.lens.data.common.constant.Constants.REDIS_KEY_SESSION;

/**
 * Description:
 *
 * @author WeiShaoying
 * @date 2019-11-06
 */
@Component("authentication" + SecuritytConstants.LENS)
public class NativeAuthentication implements Authentication {

    /**
     * lens用户session timeout单位为分
     * 默认一天 即1440分钟
     */
    @Value("${lens.security.session.timeout:1440}")
    private long sessionTimeOut;

    @Autowired
    LensAuthService lensAuthService;
    @Autowired
    private RedisClient redisClient;

    @Override
    public int authentication(HttpServletRequest request) {
        String sessionId = request.getHeader(SecuritytConstants.AUTHORIZATION);
        if (StringUtils.isEmpty(sessionId)) {
            return HttpServletResponse.SC_UNAUTHORIZED;
        }
        String val = redisClient.getAndTouch(REDIS_KEY_SESSION + sessionId, sessionTimeOut, TimeUnit.MINUTES);
        if (StringUtils.isEmpty(val)) {
            return HttpServletResponse.SC_UNAUTHORIZED;
        }
        LensUser lensUser = lensAuthService.findLensUserByUserName(val);
        if (null == lensUser) {
            return HttpServletResponse.SC_UNAUTHORIZED;
        }
        User user = new User();
        user.setUid(lensUser.getId().toString());
        user.setEmail(lensUser.getEmail());
        user.setUsername(lensUser.getName());
        user.setName(lensUser.getName());
        user.setUserType(Constants.UserTypeEnum.LENS.getCode());
        //检查lens系统资源权限
        return lensAuthService.checkPermission(user, request.getRequestURI(), request) ? HttpServletResponse.SC_OK : HttpServletResponse.SC_FORBIDDEN;
    }
}
